import dayjs from 'dayjs'
import type {
  SqlError, Node, Identifier, Ast,
} from '@/types/retrieval-sql'
import type { PatentIdentifier } from '@/types'

export function findIdentifier(identifiers: PatentIdentifier[], input: string) {
  let name = input.toUpperCase()
  const find = identifiers.find((it) => (name === it.key.toUpperCase() || it.alias?.toUpperCase() === name || it.name.toUpperCase() === name))
  if (find) return find

  // 精确
  if (!name.endsWith('(精确)')) return undefined
  name = name.substring(0, name.length - 4)
  return identifiers
    .filter((it) => it.type === 'term')
    .find((it) => (name === it.key.toUpperCase() || it.alias?.toUpperCase() === name || it.name.toUpperCase() === name))
}

export function syntaxError(reason: Omit<SqlError, 'type'>): SqlError {
  return {
    ...reason,
    type: 'SyntaxError',
  }
}

export function typeError(reason: Omit<SqlError, 'type'>): SqlError {
  return {
    ...reason,
    type: 'SyntaxError',
  }
}

export function hasIdentifier(ast: Ast, key: string) {
  function walk(node: Node): boolean {
    switch (node.type) {
      case 'Expression':

        if (node.left && walk(node.left)) {
          return true
        }
        return !!(node.right && walk(node.right))
      case 'Identifier':
        return (node as Identifier).name === key
      case 'Literal':
      default:
        return false
    }
  }
  return walk(ast)
}

export function getDate(input: string, end = false) {
  let date = dayjs(input, ['YYYY', 'YYYY-MM-DD', 'YYYY-MM', 'YYYY.MM.DD', 'YYYY.MM', 'YYYYMMDD', 'YYYYMM'], true)
  if (!date.isValid()) {
    return null
  }
  if (end) {
    if (input.length < 5) {
      date = date.endOf('year')
    } else if (input.length < 8) {
      date = date.endOf('month')
    }
  }
  return date.format('YYYY-MM-DD')
}
